package com.mes.handler.report;

import com.mes.manufacture.data.EmesoJobOrder;
import com.mes.manufacture.data.EmesoManuOrder;
import com.mes.plan.data.EmespPlanOrder;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.Query;
import org.openbravo.base.exception.OBException;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.service.OBDal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public class DataLinkTracingHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		try {
			JSONObject jsonData = new JSONObject(data);
			String orderType = jsonData.getString("orderType");
			String orderCode = jsonData.getString("orderCode");
			
			if ("计划订单".equalsIgnoreCase(orderType)) {
				getPlanOrder(orderCode, jsonRep);
			} else if ("生产订单".equalsIgnoreCase(orderType)) {
				getManuOrder(orderCode, jsonRep);
			} else if ("作业计划".equalsIgnoreCase(orderType)) {
				getJobPlan(orderCode, jsonRep);
			} else if ("作业订单".equalsIgnoreCase(orderType)) {
				getJobOrder(orderCode, jsonRep);
			} else if("外协订单".equalsIgnoreCase(orderType)){
				getOutOrder(orderCode, jsonRep);
			} else if ("planOrderList".equalsIgnoreCase(orderType)) {//点击需求计划查询所有计划订单
				jsonRep.put("planOrderList", this.getPlanOrderList(orderCode));
			} else if ("manuOrderList".equalsIgnoreCase(orderType)) {//点击计划订单查询所有生产订单
				jsonRep.put("manuOrderList", this.getManuOrderList(orderCode));
			} else if ("jobOrderList".equalsIgnoreCase(orderType)) {//点击作业几乎查询所有作业订单
				jsonRep.put("jobOrderList", this.getJobOrderList(orderCode));
			}
			
			jsonRep.put("success", true);
			jsonRep.put("msg", "数据链查询成功！");
			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			e.printStackTrace();
			OBDal.getInstance().rollbackAndClose();
			logger.error("数据链查询失败：", e);
			try {
				jsonRep.put("success", false);
				jsonRep.put("msg", "查询失败：" + e.getMessage());
			} catch (JSONException e1) {
			}
		}
		return jsonRep;
	}
	/**
	 * 通过计划订单编号查找信息，并带出需求计划与生产订单列表
	 */
	private void getPlanOrder(String code, JSONObject jsonRep) throws JSONException {
		Map order = this.getPlanOrder(code);
		if (order == null) {
			throw new OBException("未找到编码为【" + code + "】的计划订单！");
		}
		jsonRep.put("planOrder", order);
		jsonRep.put("manuOrderList", getManuOrderList((String)order.get("id")));
	}
	/**
	 * 通过生产订单编号查找信息，并带出计划订单、需求计划与作业计划列表
	 */
	private void getManuOrder(String code, JSONObject jsonRep) throws JSONException {
		Map order = this.getManuOrder(code);
		if (order == null) {
			throw new OBException("未找到编码为【" + code + "】的生产订单！");
		}
		jsonRep.put("manuOrder", order);
		jsonRep.put("planOrder", this.getPlanOrder((String)order.get("emespPlanorderCode")));
		//jsonRep.put("jobPlanList", this.getJobPlanList((String)order.get("id")));
		jsonRep.put("jobOrderList", this.getJobOrderList((String)order.get("id")));
	}
	/**
	 * 通过作业计划编号查找信息，并带出生产订单、计划订单、需求计划与作业订单列表
	 */
	private void getJobPlan(String code, JSONObject jsonRep) throws JSONException {
		Map plan = this.getManuOrder(code);
		if (plan == null) {
			throw new OBException("未找到编码为【" + code + "】的作业计划！");
		}
		jsonRep.put("manuOrder", plan);
		jsonRep.put("planOrder", this.getPlanOrder((String)plan.get("emespPlanorderCode")));
		jsonRep.put("jobOrderList", this.getJobOrderList((String)plan.get("id")));
	}
	/**
	 * 通过作业订单编号查找信息，并带出生产订单、计划订单、需求计划、作业计划
	 */
	private void getJobOrder(String code, JSONObject jsonRep) throws JSONException {
		Map order = this.getJobOrder(code);
		if (order == null) {
			throw new OBException("未找到编码为【" + code + "】的作业订单！");
		}
		jsonRep.put("jobOrder", order);
		jsonRep.put("manuOrder", this.getManuOrder((String)order.get("emesoManuorderCode")));
		jsonRep.put("planOrder", this.getPlanOrder((String)order.get("emespPlanorderCode")));
	}
	/**
	 * 通过外协订单编号查找信息，并带出生产订单、计划订单、需求计划
	 */
	private void getOutOrder(String code, JSONObject jsonRep) throws JSONException {
		Map order = this.getOutOrder(code);
		if (order == null) {
			throw new OBException("未找到编码为【" + code + "】的外协订单！");
		}
		jsonRep.put("OutOrder", order);
		jsonRep.put("manuOrder", this.getManuOrder((String)order.get("emesoManuorderCode")));
		jsonRep.put("planOrder", this.getPlanOrder((String)order.get("emespPlanorderCode")));
	}

	//外协订单SQL语句
	private Map getOutOrder(String code){
		return null;
	}

	private Map getPlanOrder(String code) {
		String hql = "select new map(e.id as id, e.code as code, e.name as name, e.qty as qty, e.qtyDone as qtyDone, " +
				"e.executeDateFrom as executeDateFrom, e.executeDateTo as executeDateTo, e.status as status, " +
				//"e.emespDemandplan.code as emespDemandplanCode, " +
				//"e.topProduct.searchKey as topProduct, " +
				"e.product.searchKey as product) " +
				"from " + EmespPlanOrder.ENTITY_NAME + " e where e.code = :code";
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("code", code);
		return (Map)query.uniqueResult();
	}
	
	private List getPlanOrderList(String demandId) {
		String hql = "select new map(e.id as id, e.code as code, e.name as name, e.qty as qty, e.qtyDone as qtyDone, " +
				"e.executeDateFrom as executeDateFrom, e.executeDateTo as executeDateTo, e.status as status, " +
				"e.topProduct.searchKey as topProduct, e.product.searchKey as product) " +
				"from " + EmespPlanOrder.ENTITY_NAME + " e where e.emespDemandplan.id = :id";
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("id", demandId);
		return toJosnList(query.list());
	}
	
	private Map getManuOrder(String code) {
		String hql = "select new map(e.id as id, e.code as code, e.name as name, " +
				"e.qty as qty, e.qtyDone as qtyDone, e.qtyStarted as qtyStarted, e.status as manuorderStatus, " +
				"e.batchNo as batchNo, e.seqNo as seqNo," +
				"e.emespPlanorder.code as emespPlanorderCode, " +
				//"e.emespPlanorder.emespDemandplan.code as emespDemandplanCode, " +
				//"e.topProduct.searchKey as topProduct, " +
				"e.product.searchKey as product, e.organization.name as departmentname) " +
				"from " + EmesoManuOrder.ENTITY_NAME + " e " +
				"where e.code = :code";
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("code", code);
		return (Map)query.uniqueResult();
	}
	
	private List getManuOrderList(String planOrderId) {
		String hql = "select new map(e.id as id, e.code as code, e.name as name, " +
				"e.qty as qty, e.qtyDone as qtyDone, e.qtyStarted as qtyStarted, e.status as manuorderStatus, " +
				//"e.topProduct.searchKey as topProduct, " +
				"e.product.searchKey as product, " +
				"e.batchNo as batchNo, e.seqNo as seqNo) " +
				"from " + EmesoManuOrder.ENTITY_NAME + " e where e.emespPlanorder.id = :id";
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("id", planOrderId);
		return toJosnList(query.list());
	}
	
	private Map getJobOrder(String code) {
		String hql = "select new map(e.id as id, e.code as code, e.qty as qty, e.qtyDone as qtyDone, " +
				"sta.name as emesStation, e.routeName as routeName, " +
				"rgroup.name as resourceGroup, " +
				"res.name as resource, " +
				"e.qtyStart as qtyStart, e.status as jobStatus,de.name as department, " +
				"e.qtyGood as qtyGood, e.qtyError as qtyError, e.exeDateFrom as exeDateFrom, e.exeDateTo as exeDateTo, " +
				"e.emesoManuorderJob.code as emesoManuorderJobCode, " +
				"e.emesoManuorderJob.emesoManuorder.code as emesoManuorderCode," +
				"e.emesoManuorderJob.emesoManuorder.emespPlanorder.code as emespPlanorderCode) " +
				"from " + EmesoJobOrder.ENTITY_NAME + " e " +
				"left join e.emesDepartment de " +
				"left join e.emesResourceGroup rgroup " +
				"left join e.emesResource res " +
				"left join e.emesStation sta " +
				"where e.code = :code";
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("code", code);
		return (Map)query.uniqueResult();
	}
	
	private List getJobOrderList(String jobId) {
		String hql = "select new map(e.id as id, e.code as code, e.qty as qty, e.qtyDone as qtyDone, " +
				"sta.name as emesStation, e.routeName as routeName, " +
				"rgroup.name as resourceGroup, " +
				"res.name as resource, " +
				"e.qtyStart as qtyStart, e.status as jobStatus, user.name as userName," +
				"e.qtyGood as qtyGood, e.qtyError as qtyError, e.exeDateFrom as exeDateFrom, e.exeDateTo as exeDateTo) " +
				"from " + EmesoJobOrder.ENTITY_NAME + " e " +
				"left join e.emesDepartment de " +
				"left join e.emesResourceGroup rgroup " +
				"left join e.emesResource res " +
				"left join e.emesStation sta " +
				"where e.emesoManuorder.id = :id";
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("id", jobId);
		return toJosnList(query.list());
	}
	
	private List<JSONObject> toJosnList(List<Map> list) {
		List<JSONObject> result = new ArrayList<JSONObject>();
		try {
			JSONObject obj = null;
			for (Map map : list) {
				obj = new JSONObject();
				for (Object key : map.keySet()) {
					obj.put((String)key, map.get(key));
				}
				result.add(obj);
			}
		} catch (Exception e) {
		}
		return result;
	}
}
